<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/9 0009
 * Time: 下午 2:50
 */
namespace app\admin\controller;

use app\admin\model\Module;

use think\Cache;
use think\Controller;

class Base extends Controller
{

    protected $menu = null; //Current Menu Obj
    protected $model = ''; //Model Name
    protected $access = [];

	public function _initialize()
    {
    	parent::_initialize();

        // 获取当前菜单
        $module = $this->request->module();
        $controller = $this->request->controller();
        $action = $this->request->action();
        $this->menu = Module::where('path', $module . '/' . $controller . '/index')->find();

        // check route auth
        $this->authCheck();

        // Get local location
        $this->assign('bcn', $this->getLocation());
        // Get menu (初始化后台菜单)
        $this->assign('sidebar', $this->menuHtml($this->menuJson()));
        // Get tabs
        $this->assign('tabs', $this->getTabs());
        $this->assign('currentUrl', $this->request->url());
    }

    /**
     * Check route auth
     */
    private function authCheck()
    {
        $session_admin_id = session('TENANT_ID');
        if (!empty($session_admin_id)) {
            $user = model('operator')->alias('a')->join('tenant b','a.tenantId=b.id')->field('a.*,b.name tName,b.imgUrl tImgUrl')->where(['a.id' => session('member')['id']])->find();

            if (!$this->checkAccess()) {
                $this->error("您没有访问权限！");
            }
            $this->assign("admin", $user);
            /*
            $member = session('member');
            $moduleMdl = new Module();

            if($member['roleType'] === 0 ) {  //超级管理员登录，有全部权限
                $modules = $moduleMdl->toTree('',true);
            } else {  //根据权限取对应菜单
                $modules = $moduleMdl->toTree($member['moduleIds']);
            }

            $this->assign('modules',$modules);
            */
        } else {
            if ($this->request->isPost()) {
                $this->error("您还没有登录！", url("admin/login/index"));
            } else {
                header("Location:" . url("admin/login/index"));
                exit();
            }
        }
    }

    private function checkAccess() {
        $user = session('member');
        $this->assign('admin',$user);

        // 若登录账号为超级管理员，则不需要验证
        if ($user['roleType'] === 0 || $user['roleType'] == 1) {
            return true;
        }

        $module     = $this->request->module();
        $controller = $this->request->controller();
        $this->access = explode(',', $user['moduleIds']);
        //$action     = $this->request->action();
        // 不验证操作方法，默认能访问本控制器内所有方法，实际功能实现也请以一个权限对应一个控制器
        $path = strtolower($module.'/'.$controller.'/'.'index');
        if($path == 'admin/index/index'){
            return true;
        }
        if(!$this->menu){
            $this->error('该页面不存在！');
        }

        if(!in_array($this->menu->id, $this->access) || !stripos($this->menu->path, $controller)){
            return false;
        }

        return true;
    }

    /**
     * Cache menu
     *
     * @param null $data
     * @return bool|null
     */
    public function menuCache($data = null) {
        if (empty($data)) {
            $data = Module::getTree(0);
            // 缓存
            Cache::set('admin_menu', $data, 3600*6);
        } else {
            Cache::set('admin_menu', $data, 3600*6);
        }
        return $data;
    }

    /**
     * 菜单树状结构集合
     */
    public function menuJson() {
        $menu = Cache::get('admin_menu');
        if (!$menu) {
            $menu = $this->menuCache();
        }
        return $menu;
    }

    /**
     * 菜单
     * @param $menus
     * @return string
     */
    public function menuHtml($menus) {
        if($menus){
            $subMenu = function ($menus, $level = 0) use (&$subMenu) {
                $output = '';
                foreach($menus as $menu){
                    // 检查菜单权限
                    if (!in_array($menu['id'], $this->access) && session('member')['roleType'] == 2) {
                        continue;
                    }
                    $uri = $this->request->path();
                    $uri_arr = explode('/', $uri);
                    count($uri_arr) < 2 && $uri_arr[1] = 'index';
                    if(count($uri_arr) < 3 || preg_match('/add/', $uri_arr[2]) || preg_match('/edit/', $uri_arr[2]) || (isset($uri_arr[3]) && $uri_arr[3] == 'id')){
                        $uri_arr[2] = 'index';
                    }
                    if($menu['parent']){
                        $icon = !empty($menu['icon']) ? $menu['icon'] : 'fa fa-circle-o';
                    }else{
                        $icon = $menu['icon'];
                    }
                    if(($uri_arr[0] == $menu['app'] && lcfirst($uri_arr[1]) == $menu['controller'])){
                        $active = 'active';
                    }else{
                        $active = '';
                    }

                    if(empty($menu['items'])){
                        $output .= '<li class="treeview '.$active.'">';
                        $output .= '<a href="'.$menu['url'].'" target="'.$menu['target'].'">';
                        $output .= '<i class="'.$icon.'"></i>';
                        $output .= '<span> '.lang($menu['name']).' </span>';
                        $output .= '</a>';
                        $output .= '</li>';
                    }else{
                        $module = $this->request->module();
                        $controller = lcfirst($this->request->controller());
                        $action = $this->request->action();
                        $current = Module::where(['path' => $module . '/' . $controller . '/index'])->find();
                        $parentIds = $this->getParentIds($current['typeId']);
                        $parentIdsArr = explode(',' , $parentIds);
                        $class = 'active';
                        if($level >= 2){
                            $class = 'menu-open';
                        }
                        $output .= '<li class="treeview '.(in_array($menu['id'], $parentIdsArr) ? $class : '').'">';
                        $menu['url'] = 'javascript:void(0);';
                        $output .= '<a href="'.$menu['url'].'" target="'.$menu['target'].'">';
                        $output .= '<i class="'.$icon.'"></i>';
                        $output .= '<span> '.lang($menu['name']).' </span>';
                        $output .= '<i class="fa fa-angle-left pull-right"></i>';
                        $output .= '</a>';
                        $output .= '<ul class="treeview-menu">';
                        $output .= $subMenu($menu['items'], $level + 1);
                        $output .= '</ul>';
                        $output .= '</li>';
                    }
                }
                return $output;
            };
            $output = $subMenu($menus);

            return $output;
        }
    }

    // 得到父辈、爷辈、祖辈...的集合
    public function getParentIds($parentId, $level = 0) {
        $result = Module::where(['id' => $parentId])->find();
        $parentIds = $result['id'];

        if($result['typeId']){
            $level = $level + 1;
            $parentIds .= ',' . $this->getParentIds($result['typeId'], $level);
        }
        return $parentIds;
    }

    private function getLocation() {
        //BCN
        $bcn = '';
        if ($this->menu) {
            //set page title with translation
            $trans_title_key = strtolower(str_replace(' ', '_', $this->menu->name));
            if (lang($trans_title_key) == $trans_title_key) {
                $this->assign('title', $this->menu->name);
            } else {
                $this->assign('title', lang( $trans_title_key));
            }

            //set bcn by Closure menu
            $recursive = function ($id, $output) use (&$recursive) {
                $menu = Module::find($id);
                $trans_title_key = strtolower(str_replace(' ', '_', $menu->name));
                $title = $menu->name;
                if (lang($trans_title_key) != $trans_title_key) {
                    $title = lang($trans_title_key);
                }
                $link = '<li>';
                if ($this->menu->id == $id) {
                    $link .= '<span>' . $title . '</span>';
                } else {
                    if($menu->typeId){
                        // TODO
                        $menu->route = $menu->path != '#' ? strtolower($menu->path) : 'javascript:void(0);';
                        $target = $menu->target ? 'target="'.$menu->target.'"' : '';
                        $link .= '<a href="'.url($menu->path).'" title="'.$title.'" '.$target.'>'.$title.'</a>';
                    }else{
                        $link .= '<span>' . $title . '</span>';
                    }
                }
                $link .= '</li>';

                array_unshift($output, $link);

                if ($menu->typeId) {
                    $output = $recursive($menu->typeId, $output);
                }
                return $output;
            };

            $bcn = $this->view->fetch('public/bcn', ['breadcrumbs' => $recursive($this->menu->id, [])]);
            return $bcn;
        }
    }

    private function getTabs() {
        //tabs
        $tabs = '';
        if ($this->menu) {
            $menus = Module::where(['typeId' => $this->menu->typeId])->order('sorting', 'asc')->order('id', 'asc')->select();
            if ($menus) {
                foreach ($menus as $menu) {
                    //title
                    $trans_title_key = strtolower(str_replace(' ', '_', $menu->name));
                    $title = $menu->name;
                    if (lang($trans_title_key) != $trans_title_key) {
                        $title = lang($trans_title_key);
                    }
                    $tabs .= '<li' . ($this->menu->id == $menu->id ? ' class="active"' : '') . '>';
                    $menu->route = strtolower($menu->path);
                    $tabs .= '<a href="' . url($this->request->path(), $this->request->param('id') ? $this->request->param('id') : '') . '" title="' . $title . '">' . $title . '</a>';
                    $tabs .= '</li>';
                }
            }
            return $tabs;
        }
    }

    public function checkStore() {  //检测是否已有门店，若无，提示去创建门店，并跳转
        $find = \app\admin\model\Store::where('tenantId',session('TENANT_ID'))->find();
        if($find) {
            return true;
        }
        return false;
    }

}